﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.Manufacture;
using RedDragon.Common.Dtos;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.API.Application.Commands.WorkCenter;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;
using Yitter.IdGenerator;

namespace RedDragon.ERP.API.Application.Commands.Resource
{
    public class CreateResourceHandlerr : IRequestHandler<CreateResourceCommand, Result>
    {
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 资源仓储
        /// </summary>
        public readonly IBaseRepository<Resources> resourcesRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreateResourceHandlerr> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="resourcesRepository"></param>
        /// <param name="logger"></param>
        public CreateResourceHandlerr(IMapper mapper, IBaseRepository<Resources> resourcesRepository, ILogger<CreateResourceHandlerr> logger)
        {
            this.mapper = mapper;
            this.resourcesRepository = resourcesRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 添加资源
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(CreateResourceCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                Resources resources = mapper.Map<Resources>(request);
                //权限编号雪花ID
                resources.ResourceCode = YitIdHelper.NextId().ToString();
                var res = await resourcesRepository.Add(resources);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "资源添加成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "资源添加失败" + ex.Message;
                logger.LogError("资源添加失败" + ex.Message);
            }
            return result;
        }
    }
}
